using System;

namespace Tycho.Parser.Peg {
    public class OptionalRule : Rule {
        public readonly IRule SubRule;

        public OptionalRule (IRule subRule) {
            SubRule = subRule;
        }

        public override Yield Parse (char[] source, int index, ParseContext context, string sourceString, ParseEnvironment environment, Func<RuleParseResult, Yield> continuation) {
            return SubRule.Parse (source, index, context, sourceString, environment, result => {
                if (result == null) {
                    return () => continuation (new RuleParseResult (index, context));
                } else {
                    return () => continuation (result);
                }
            });
        }
    }
}